/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package megamar;

import com.toedter.calendar.IDateEditor;
import com.toedter.calendar.JDateChooser;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.text.JTextComponent;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import reportes.MetodosImpresion;

/**
 *
 * @author pedro.lizondo
 */
public class Creditos extends javax.swing.JFrame {

    private String idzona;
    private int num_creditos;
    private int id_cliente;
    private float compra_total;
    private boolean clientevalido;
    private String tipo_sistema;
    public static final SimpleDateFormat FORMATO_YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd"); //Here put your format
    public DefaultComboBoxModel value;
    /**
     * Creates new form creditos
     */
    public Creditos(String idz, String nomzona, java.awt.Frame parent, boolean modal, String sistema) {
        //super(parent, modal);
        initComponents();
        jdfechacredito.setLocale(Locale.getDefault());  //Define el idioma del calendar
        IDateEditor editorDC = (IDateEditor) jdfechacredito.getDateEditor();
        editorDC.getUiComponent().addKeyListener(new KeyListener() {

            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == e.VK_ENTER) {
                    txtcreditoinicial.requestFocusInWindow();                    
                }
            }

            public void keyReleased(KeyEvent keyEvent) {
                //printIt("Released", keyEvent);
            }

            public void keyTyped(KeyEvent keyEvent) {
                //printIt("Typed", keyEvent);
            }
        });
        
        idzona = idz;
        tipo_sistema = sistema;
        //labelzona.setText(nomzona);
        this.setLocationRelativeTo(null);
        completarcomboplan();
        txtcodigocliente.requestFocusInWindow();
    }

    public boolean getclientevalido() {
        return clientevalido;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButtonAceptar = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel15 = new javax.swing.JLabel();
        txtcodigocliente = new javax.swing.JTextField();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jbvercreditos = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtcreditoinicial = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtinteres = new javax.swing.JTextField();
        jdfechacredito = new com.toedter.calendar.JDateChooser("dd/MM/yyyy", "##/##/##", '_');
        jLabel8 = new javax.swing.JLabel();
        txtcuota = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        txtcomision = new javax.swing.JTextField();
        comboplanes = new javax.swing.JComboBox();
        jPanel5 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jLabel16 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        jPanel7 = new javax.swing.JPanel();
        txtdni = new javax.swing.JTextField();
        txtnombre = new javax.swing.JTextField();
        txtdomicilioparticular = new javax.swing.JTextField();
        txtbarrioparticular = new javax.swing.JTextField();
        jPanel8 = new javax.swing.JPanel();
        jLabel14 = new javax.swing.JLabel();
        jLabel23 = new javax.swing.JLabel();
        jLabel24 = new javax.swing.JLabel();
        jLabel25 = new javax.swing.JLabel();
        jPanel9 = new javax.swing.JPanel();
        txtdomiciliocomercial = new javax.swing.JTextField();
        txtbarriocomercial = new javax.swing.JTextField();
        txttelefono = new javax.swing.JTextField();
        txtrubro = new javax.swing.JTextField();
        jButton6 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablacreditos = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jButtonImprimirCredito = new javax.swing.JButton();
        jButtonEliminarCredito = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Creditos");

        jButtonAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Ok.png"))); // NOI18N
        jButtonAceptar.setText("Aceptar");
        jButtonAceptar.setPreferredSize(new java.awt.Dimension(111, 41));
        jButtonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAceptarActionPerformed(evt);
            }
        });
        jButtonAceptar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jButtonAceptarKeyPressed(evt);
            }
        });

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Buscar Cliente"));

        jLabel15.setText("Codigo");

        txtcodigocliente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtcodigoclienteKeyPressed(evt);
            }
        });

        jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Sherlocks_Tool.png"))); // NOI18N
        jButton7.setText("Buscar");
        jButton7.setPreferredSize(new java.awt.Dimension(111, 41));
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jButton8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/clientes_32.png"))); // NOI18N
        jButton8.setText("Ver Listado de Clientes");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        jbvercreditos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/clientes_32.png"))); // NOI18N
        jbvercreditos.setText("Ver Creditos del Cliente");
        jbvercreditos.setEnabled(false);
        jbvercreditos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbvercreditosActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel15)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtcodigocliente, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbvercreditos, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(180, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(txtcodigocliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton8)
                    .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbvercreditos))
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del Crédito"));

        jLabel2.setText("Fecha de Crédito");

        jLabel3.setText("Crédito incial ($)");

        jLabel4.setText("Plan (semanas)");

        txtcreditoinicial.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtcreditoinicialKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtcreditoinicialKeyReleased(evt);
            }
        });

        jLabel6.setText("Interés (%)");

        txtinteres.setEditable(false);

        jLabel8.setText("Cuota ($)");

        txtcuota.setEditable(false);

        jLabel10.setText("Comision Cobrador (%)");

        txtcomision.setEditable(false);

        comboplanes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboplanesActionPerformed(evt);
            }
        });
        comboplanes.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                comboplanesKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jdfechacredito, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtcreditoinicial, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jLabel4))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(comboplanes, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtinteres, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(txtcuota, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel10)
                    .addComponent(txtcomision, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(214, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jLabel8)
                            .addComponent(jLabel10))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtinteres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtcuota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtcomision, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2)
                                .addComponent(jLabel4)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jdfechacredito, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(txtcreditoinicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(comboplanes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del Cliente"));

        jPanel6.setLayout(new java.awt.GridLayout(4, 0, 5, 5));

        jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel16.setText("DNI");
        jPanel6.add(jLabel16);

        jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel9.setText("Apellido y Nombre");
        jPanel6.add(jLabel9);

        jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel17.setText("Domicilio Particular");
        jPanel6.add(jLabel17);

        jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel20.setText("Barrio Particular");
        jPanel6.add(jLabel20);

        jPanel7.setLayout(new java.awt.GridLayout(4, 0, 5, 5));

        txtdni.setEditable(false);
        jPanel7.add(txtdni);

        txtnombre.setEditable(false);
        jPanel7.add(txtnombre);

        txtdomicilioparticular.setEditable(false);
        jPanel7.add(txtdomicilioparticular);

        txtbarrioparticular.setEditable(false);
        jPanel7.add(txtbarrioparticular);

        jPanel8.setLayout(new java.awt.GridLayout(4, 0, 5, 5));

        jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel14.setText("Domicilio Comercial");
        jPanel8.add(jLabel14);

        jLabel23.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel23.setText("Barrio Comercial");
        jPanel8.add(jLabel23);

        jLabel24.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel24.setText("Teléfono");
        jPanel8.add(jLabel24);

        jLabel25.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel25.setText("Rubro");
        jPanel8.add(jLabel25);

        jPanel9.setLayout(new java.awt.GridLayout(4, 0, 5, 5));

        txtdomiciliocomercial.setEditable(false);
        jPanel9.add(txtdomiciliocomercial);

        txtbarriocomercial.setEditable(false);
        jPanel9.add(txtbarriocomercial);

        txttelefono.setEditable(false);
        jPanel9.add(txttelefono);

        txtrubro.setEditable(false);
        jPanel9.add(txtrubro);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap(123, Short.MAX_VALUE)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(60, 60, 60)
                .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(71, 71, 71))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel9, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Cancel.png"))); // NOI18N
        jButton6.setText("Cancelar");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        tablacreditos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tablacreditos.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        tablacreditos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                tablacreditosMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tablacreditos);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jButtonImprimirCredito.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/printer_32.png"))); // NOI18N
        jButtonImprimirCredito.setText("Imprimir Credito Seleccionado");
        jButtonImprimirCredito.setEnabled(false);
        jButtonImprimirCredito.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImprimirCreditoActionPerformed(evt);
            }
        });

        jButtonEliminarCredito.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/recycle_32.png"))); // NOI18N
        jButtonEliminarCredito.setText("Eliminar Credito Seleccionado");
        jButtonEliminarCredito.setEnabled(false);
        jButtonEliminarCredito.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEliminarCreditoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonImprimirCredito)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonEliminarCredito)
                .addContainerGap(423, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonImprimirCredito)
                    .addComponent(jButtonEliminarCredito))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 859, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton6))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jbvercreditosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbvercreditosActionPerformed
    CreditosClientesHistorial C = new CreditosClientesHistorial(this, true, id_cliente);
    C.setVisible(true);
}//GEN-LAST:event_jbvercreditosActionPerformed

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
    ListadoClientes L = new ListadoClientes(idzona, this, true);
    L.setVisible(true);
    if (L.getidcliente().equals("")) {
        //return;
    } else {
        txtcodigocliente.setText(L.getidcliente());
        cargardatos();
        jbvercreditos.setEnabled(true);
        cargartablacreditos();
        jdfechacredito.setDate(new Date());
        jdfechacredito.requestFocusInWindow();
        //Para posicionar el cursor al principio de la fecha//
        JTextComponent jt = (JTextComponent) jdfechacredito.getDateEditor();
        jt.setCaretPosition(0);
    }
}//GEN-LAST:event_jButton8ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        if (txtcodigocliente.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Ingrese el codigo del cliente o presione el boton Ver listado de Clientes.", "ERROR", JOptionPane.ERROR_MESSAGE);
        } else {
            cargardatos();
            if (getclientevalido() == true) {
                cargartablacreditos();
                jdfechacredito.setDate(new Date());
                jdfechacredito.requestFocusInWindow();
                //Para posicionar el cursor al principio de la fecha//
                JTextComponent jt = (JTextComponent) jdfechacredito.getDateEditor();
                jt.setCaretPosition(0);
                jbvercreditos.setEnabled(true);
            }
        }
    }//GEN-LAST:event_jButton7ActionPerformed

    private void txtcreditoinicialKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtcreditoinicialKeyReleased
        if (comboplanes.getSelectedIndex() == 0 || txtinteres.getText().equals("")) {
            //return
        } else {
            int credito = Integer.parseInt(txtcreditoinicial.getText());
            int interes = Integer.parseInt(txtinteres.getText());
            int plan = Integer.parseInt(comboplanes.getSelectedItem().toString());
            compra_total = (credito * interes) / 100 + credito;
            float cuota = compra_total / plan;
            txtcuota.setText(Float.toString(cuota));
        }
    }//GEN-LAST:event_txtcreditoinicialKeyReleased

    private void comboplanesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboplanesActionPerformed
        ComboboxItem selected_item = (ComboboxItem) comboplanes.getSelectedItem();
        String consulta = "Select interes, comision from plan where idplan = '" + selected_item.getId() + "' ";
        if (comboplanes.getSelectedIndex() == 0) {
            txtinteres.setText("");
            txtcuota.setText("");
            txtcomision.setText("");
        } else if (txtcreditoinicial.getText().equals("")) {
            //return
        } else {
            try {
                Conectar();
                ResultSet rs = stmt.executeQuery(consulta);
                rs.beforeFirst();
                while (rs.next()) {
                    txtinteres.setText(rs.getString("interes"));
                    txtcomision.setText(rs.getString("comision"));
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Error al cargar los PLANES.", "Error", JOptionPane.ERROR_MESSAGE);
            }
            int credito = Integer.parseInt(txtcreditoinicial.getText());
            int interes = Integer.parseInt(txtinteres.getText());
            int plan = Integer.parseInt(comboplanes.getSelectedItem().toString());
            compra_total = (credito * interes) / 100 + credito;
            float cuota = compra_total / plan;
            txtcuota.setText(Float.toString(cuota));
        }
    }//GEN-LAST:event_comboplanesActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButtonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAceptarActionPerformed
        //System.out.println((String) FORMATO_YYYY_MM_DD.format(jdfechacredito.getDate()));
        //System.out.println(jdfechacredito.getDate().toString());
        if (txtcodigocliente.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Por favor seleccione un Cliente.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (comboplanes.getSelectedIndex() == 0) {
            JOptionPane.showMessageDialog(null, "Por favor seleccione un Plan(semanas) de la lista desplegable.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (txtcreditoinicial.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Por favor ingrese el monto del credito en cuadro Credito Inicial.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int res = JOptionPane.showConfirmDialog(null, "¿Desea guardar los datos del Credito?", "Nuevo Credito", JOptionPane.YES_NO_OPTION);
        if (res == JOptionPane.YES_OPTION) {
            float compra = Float.parseFloat(txtcreditoinicial.getText());
            String plan = comboplanes.getSelectedItem().toString();
            String interes = txtinteres.getText();
            String comision = txtcomision.getText();
            String cuota = txtcuota.getText();
            String pagado = "0";
            String fecha_compra = (String) FORMATO_YYYY_MM_DD.format(jdfechacredito.getDate());
            //String fecha_ultimo_pago = "0000-00-00";
            String fecha_ultimo_pago = (String) FORMATO_YYYY_MM_DD.format(jdfechacredito.getDate());
            /*Calculo de la fecha de cancelacion*/
            Calendar c1 = Calendar.getInstance();
            c1.setTime(jdfechacredito.getDate());               //Le asignamos la fecha seleccionada en el jdfechacredito
            c1.add(Calendar.DATE, Integer.parseInt(plan) * 7);  //Le sumamos la cantidad de dias = semanas * 7
            //System.out.println("La fecha de hoy más  X días es : " + FORMATO_YYYY_MM_DD.format(c1.getTime()));
            //jdfechacredito.add(jdfechacredito.getDate(), 5);
            String fecha_cancelacion = (String) FORMATO_YYYY_MM_DD.format(c1.getTime());
            int credito_numero = num_creditos + 1;
            String estado = "DEBE";
            float saldo = compra_total;
            String idcliente = txtcodigocliente.getText();

            /*Alta del CREDITO*/
            String consulta = "insert into credito (compra,compra_total,plan,interes,comision,cuota,pagado,fecha_compra,fecha_ultimo_pago,fecha_cancelacion,credito_numero,estado,saldo,idcliente,atraso_total,incremento_total) "
                    + "values('" + compra + "', '" + compra_total + "', '" + plan + "', '" + interes + "', '" + comision + "', '" + cuota + "', '" + pagado + "', '" + fecha_compra + "', '" + fecha_ultimo_pago + "', "
                    + " '" + fecha_cancelacion + "', '" + credito_numero + "', '" + estado + "', '" + saldo + "', '" + idcliente + "',0,0 )";
            try {
                Conectar();
                int done = stmt.executeUpdate(consulta);
                //JOptionPane.showMessageDialog(null,"alta","Aviso",JOptionPane.INFORMATION_MESSAGE);
                JOptionPane.showMessageDialog(null, "Se guardaron los datos del Credito.", "Aviso", JOptionPane.INFORMATION_MESSAGE);
                db.close(stmt);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Error! No se pudo cargar los datos del cliente", JOptionPane.ERROR_MESSAGE);
            }
            db.destroy();

            /*Modificacion de los datos del Cliente*/
            String consulta2 = "update cliente "
                    + "set num_creditos='" + credito_numero + "', estado='ACTIVO' "
                    + "where idcliente='" + idcliente + "'";

            try {
                Conectar();
                int done = stmt.executeUpdate(consulta2);
                //JOptionPane.showMessageDialog(null,"alta","Aviso",JOptionPane.INFORMATION_MESSAGE);
                //JOptionPane.showMessageDialog(null,"Se actualizaron los datos de la zona.","Aviso", JOptionPane.INFORMATION_MESSAGE);
                db.close(stmt);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Error! No se pudo actualizar los datos del Cliente.", JOptionPane.ERROR_MESSAGE);
            }
            db.destroy();
            this.dispose();
        }
    }//GEN-LAST:event_jButtonAceptarActionPerformed

    private void txtcodigoclienteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtcodigoclienteKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            jButton7.doClick();
        }
    }//GEN-LAST:event_txtcodigoclienteKeyPressed

    private void txtcreditoinicialKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtcreditoinicialKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            comboplanes.requestFocus();
        }
    }//GEN-LAST:event_txtcreditoinicialKeyPressed

    private void comboplanesKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_comboplanesKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            jButtonAceptar.requestFocus();
        }
    }//GEN-LAST:event_comboplanesKeyPressed

    private void jButtonAceptarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButtonAceptarKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            jButtonAceptar.doClick();
        }
    }//GEN-LAST:event_jButtonAceptarKeyPressed

    private void jButtonImprimirCreditoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImprimirCreditoActionPerformed
        String id = String.valueOf(tablacreditos.getValueAt(tablacreditos.getSelectedRow(), 0));
        try {
            new MetodosImpresion().ReporteCuentaCorrienteCliente(id);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Creditos.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Creditos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonImprimirCreditoActionPerformed

    private void jButtonEliminarCreditoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarCreditoActionPerformed
        int res = JOptionPane.showConfirmDialog(null, "¿Desea eliminar el credito seleccionado?", "Eliminar Credito", JOptionPane.YES_NO_OPTION);
        if (res == JOptionPane.YES_OPTION) {
            String id = String.valueOf(tablacreditos.getValueAt(tablacreditos.getSelectedRow(), 0));
            String consulta = "Select * from pago where idcredito = '" + id + "' ";
            try {
                Conectar();
                ResultSet rs = stmt.executeQuery(consulta);
                rs.last();
                if (rs.getRow() == 0) {
                    //SI EL CLEINTE NO TIENE PAGOS DE ESE CREDITO, ELIMINAMOS EL CREDITO//
                    consulta = "delete from credito where idcredito='" + id + "' ";
                    int done = stmt.executeUpdate(consulta);
                } else {
                    JOptionPane.showMessageDialog(null, "No se puede eliminar el Credito seleccionado porque este registra Pagos.\nVerifique el historial de los Pagos.", "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                db.close(stmt);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Error al verificar los Pagos del Credito", "Error", JOptionPane.ERROR_MESSAGE);
            }
            
            //SE ACTUALIZA EL CAMPO num_creditos DEL CLIENTE//
            consulta = "UPDATE cliente SET num_creditos = num_creditos - 1 WHERE idcliente = '" + id_cliente + "'";
            try {
                Conectar();
                int done = stmt.executeUpdate(consulta);
                JOptionPane.showMessageDialog(null, "Se eliminaron todos los datos del Credito seleccionado.", "Eliminar Credito", JOptionPane.INFORMATION_MESSAGE);
                db.close(stmt);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Error al actualizar el numero de creditos del cliente", "Error", JOptionPane.ERROR_MESSAGE);
            }
            this.dispose();
        }
    }//GEN-LAST:event_jButtonEliminarCreditoActionPerformed

    private void tablacreditosMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablacreditosMouseReleased
        if(tablacreditos.getSelectedRow() >= 0){
            jButtonImprimirCredito.setEnabled(true);
            jButtonEliminarCredito.setEnabled(true);
        }
    }//GEN-LAST:event_tablacreditosMouseReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Creditos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Creditos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Creditos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Creditos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        /*java.awt.EventQueue.invokeLater(new Runnable() {
        
        public void run() {
        new Creditos().setVisible(true);
        }
        });*/
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox comboplanes;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButtonAceptar;
    private javax.swing.JButton jButtonEliminarCredito;
    private javax.swing.JButton jButtonImprimirCredito;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel25;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbvercreditos;
    private com.toedter.calendar.JDateChooser jdfechacredito;
    private javax.swing.JTable tablacreditos;
    private javax.swing.JTextField txtbarriocomercial;
    private javax.swing.JTextField txtbarrioparticular;
    private javax.swing.JTextField txtcodigocliente;
    private javax.swing.JTextField txtcomision;
    private javax.swing.JTextField txtcreditoinicial;
    private javax.swing.JTextField txtcuota;
    private javax.swing.JTextField txtdni;
    private javax.swing.JTextField txtdomiciliocomercial;
    private javax.swing.JTextField txtdomicilioparticular;
    private javax.swing.JTextField txtinteres;
    private javax.swing.JTextField txtnombre;
    private javax.swing.JTextField txtrubro;
    private javax.swing.JTextField txttelefono;
    // End of variables declaration//GEN-END:variables
    private conexion db;
    private Statement stmt;

    public void Conectar() {
        try {
            db = new conexion();      //instancia de la clase conexion.java
            db.init();
            Connection conn = db.getMyConnection();
            stmt = conn.createStatement();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Problemas al concetarse a la Base de Datos", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void completarcomboplan() {
        String consulta = "Select * from plan where tipo_sistema = '"+tipo_sistema+"'";
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.beforeFirst();
            value = new DefaultComboBoxModel();
            comboplanes.setModel(value);
            //comboplanes.addItem("-");
            value.addElement(new ComboboxItem(0, ""));
            while (rs.next()) {
                //comboplanes.addItem(rs.getString(1));
                value.addElement(new ComboboxItem(rs.getInt(1),rs.getString(2)));
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar los PLANES.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void cargardatos() {
        id_cliente = Integer.parseInt(txtcodigocliente.getText());
        String consulta = "Select dni,apellido,nombre,domicilio_particular,barrio_particular,domicilio_comercial,barrio_comercial,telefono,num_creditos,perno,r.descripcion"
                + " from cliente c, rubro r where idcliente = '" + id_cliente + "' and idzona = '" + idzona + "' and c.idrubro = r.idrubro";
        //int i = 0;
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            rs.last();
            //System.out.println(rs.getRow());
            if (rs.getRow() == 0) {
                JOptionPane.showMessageDialog(null, "No existe ningun cliente con ese codigo. Por favor verifique el numero ingresado. ", "Error", JOptionPane.ERROR_MESSAGE);
                limpiarcampos();
                clientevalido = false;
            } else if (rs.getString("perno").equals("SI")) {
                JOptionPane.showMessageDialog(null, "El cliente seleccionado esta marcado como PERNO!. No se le puede asignar un credito. \nSi desea darle un credito debe modificar el campo PERNO en el menu Actualizaciones -> Clientes.", "Error", JOptionPane.ERROR_MESSAGE);
                limpiarcampos();
                clientevalido = false;
            } else {
                rs.beforeFirst();
                while (rs.next()) {
                    //txtidcliente.setText(rs.getString("idcliente"));
                    txtdni.setText(rs.getString("dni"));
                    txtnombre.setText(rs.getString("apellido") + ", " + rs.getString("nombre"));
                    txtdomicilioparticular.setText(rs.getString("domicilio_particular"));
                    txtbarrioparticular.setText(rs.getString("barrio_particular"));
                    txtdomiciliocomercial.setText(rs.getString("domicilio_comercial"));
                    txtbarriocomercial.setText(rs.getString("barrio_comercial"));
                    txttelefono.setText(rs.getString("telefono"));
                    txtrubro.setText(rs.getString("descripcion"));
                    num_creditos = rs.getInt("num_creditos");
                }
                clientevalido = true;
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar los datos del Cliente", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void limpiarcampos() {
        txtcodigocliente.setText("");
        txtdni.setText("");
        txtnombre.setText("");
        //txtapellido.setText("");
        txtdomicilioparticular.setText("");
        txtbarrioparticular.setText("");
        txtdomiciliocomercial.setText("");
        txtbarriocomercial.setText("");
        txttelefono.setText("");
        txtrubro.setText("");
        tablacreditos.setModel(null);
    }

    private void cargartablacreditos() {
        String consulta = "SELECT idcredito, compra as 'Compra',compra_total as 'Compra Total', plan as 'Plan', interes as 'Interes(%)',cuota as 'Cuota', "
                + "fecha_compra as 'Fecha Compra', estado as 'Estado', pagado as 'Pagado', fecha_cancelacion as 'Cancelacion', credito_numero as 'Credito Num', "
                + "comision as 'Comision(%)', saldo as 'Saldo' "
                + "FROM credito where idcliente = '" + id_cliente + "' "
                + "ORDER BY credito_numero DESC";
        /*fecha_ultimo_pago as 'Ultimo Pago'    ->   ERROR: no puede mostrar la fecha cuando es del tipo 0000-00-00*/
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
            DefaultTableModel modelo = new DefaultTableModel();
            tablacreditos.setModel(modelo);
            ConversorRSaDefaultTableModel.completar(rs, modelo);
            //codigo para ocultar la primera columna (idplan)
            tablacreditos.getColumnModel().getColumn(0).setMaxWidth(0);
            tablacreditos.getColumnModel().getColumn(0).setMinWidth(0);
            tablacreditos.getColumnModel().getColumn(0).setPreferredWidth(0);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error al cargar la tabla de Creditos de Clientes.", JOptionPane.ERROR_MESSAGE);
        }
    }
}
